package com.example.qwertie;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


public class GameActivity extends Activity {

	public static final String levelTag = "qwertie_level";
	
	ImageButton q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m;
	List<ImageButton> buttons = new ArrayList<ImageButton>();
	
	//colors for the TextViews
		int BLACK;
		int RED ;
	    int ORANGE ;
	    int YELLOW ;
		int GREEN ;
		int SHADOW ;
		
		//keeping track of the word being completed
		List<TextView> currentWord;
		TextView currentLetter;
		int currentLetterPos = 0;
		
		//the list of words:
		List<String> list_of_words = new ArrayList<String>();
		int currentWordPos = 0;
		
		//screen sizes:
				int screenHeight;
				int screenWidth;
		
		//points added to score
		final int key_score_first_try = 300;
		final int key_score_second_try = 200;
		final int key_score_third_try = 100;
		int successes = 0; // number of words consecutive words that are completed without error
		int errors = 0; // number of missed keys
		int key_score_finish_word = 5000*successes - 100*errors;
		long level = 1;
	
	private static int targetNumOfWords;
	private static int completedWords;
	private static int score;
	private int progress;
	private ProgressBar progressBar;
	
	Thread musicThread;
	boolean musicFlag = false;
	
	boolean tickerFlag = false;
	
	public GameActivity getCurrentGameActivity() {
		return this;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_game);
        
        BLACK = (int) getResources().getColor(R.drawable.Black);
        RED = (int) getResources().getColor(R.drawable.Red);
        ORANGE = (int) getResources().getColor(R.drawable.Orange);
        YELLOW = (int) getResources().getColor(R.drawable.Yellow);
        GREEN = (int) getResources().getColor(R.drawable.Green);
        SHADOW = (int) getResources().getColor(R.drawable.Shadow);
        
        // initialization of the button list, used in the swapping
        initializeButtons();
        
        // get the level  number and swap keys N times
        level = (Long) getIntent().getExtras().get(levelTag);
        swapKeys(2*level+3) ;
        
      //get screen sizes
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        screenHeight = displaymetrics.heightPixels;
        screenWidth = displaymetrics.widthPixels;
        
        //define progress bar size according to screen height
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        progressBar = (ProgressBar) findViewById(R.id.vertical_progressbar);
        progressBar.getLayoutParams().height=(int)(size.y*0.5);
        progressBar.getLayoutParams().width=(int)(size.y*0.15);
        progress=progressBar.getMax();
        progressBar.setProgressDrawable((Drawable)getResources().getDrawable(R.drawable.progress_bar_green));
        progressBar.setProgress(progressBar.getMax());
        
        initTicker();
        
        list_of_words.add("Salut");
        list_of_words.add("Ciao");
        list_of_words.add("Hello");
        
        //initialize score and number of completed words
        completedWords=0;
        targetNumOfWords = list_of_words.size();
        score=0;
        updateScore(0);
        updateSuccessCounter();
        
        
        displayWord(list_of_words.get(0));
        
        musicFlag = false;
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.gamemusic);
        Thread musicThread = new Thread(){
        	public void run(){
        		mp.start();
        		try{
        			while(true){
        				if(musicFlag==true)
        					throw new InterruptedException();
        			}
        		}
        		catch(InterruptedException e)
        		{
        			mp.stop();
        			mp.release();
        		}
        	}
        };
        musicThread.start();
        
        Log.i("QWERTIE", "Game started");
        
    }

    
    @Override
    protected void onPause() {
    	musicFlag = true;
    	tickerFlag = true;
    	super.onPause();
    }
    
    protected void onResume() {
    	super.onResume();
    	tickerFlag = false;
    }
    
    @Override
    protected void onDestroy() {
    	musicFlag = true;
    	tickerFlag = true;
    	super.onDestroy();
    }
    
    public void initTicker()
	{
    	
    	new CountDownTimer(50000, 50) {
    	     public void onTick(long millisUntilFinished) {
    	    	 int c=GREEN;
    	    	 if(tickerFlag==false) {
             		progressBar.setProgress(progress--);
             		if (progress<progressBar.getMax()*0.66 && c==GREEN)
             		{
             			progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.progress_bar_vertical));
             			c=YELLOW;
             		}
             		if (progress<progressBar.getMax()*0.33 && c==YELLOW)
             		{
             			progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.progress_bar_red));
             			c=RED;
             		}
    	    	 }
    	     }

    	     public void onFinish() {
    	    	 if(tickerFlag==false) gameOver();
    	     }
    	  }.start();
	}
    
    
    private void swapKeys(long swapNumber) {
    	Random random = new Random(); 
    	for(int i=0; i<swapNumber; i++) {
    	    
    		// get 2 different indexes...
    		int a=0, b=0;
    		while(a==b) {
    			a = random.nextInt(26);
    	        b = random.nextInt(26);
    		}
    		ImageButton buttonA = buttons.get(a);
    		ImageButton buttonB = buttons.get(b);
    		
    		// swap the drawables
    		Drawable tempDrawable = buttonA.getDrawable();
            buttonA.setImageDrawable(buttonB.getDrawable());
            buttonB.setImageDrawable(tempDrawable);
            
            // swap the tags
            Object tempTag = buttonA.getTag();
            buttonA.setTag(buttonB.getTag());
            buttonB.setTag(tempTag);
    	}
    	
    }
    
    private void initializeButtons() {
		q = (ImageButton) findViewById(R.id.imageButton1);
		w = (ImageButton) findViewById(R.id.imageButton3);
		e = (ImageButton) findViewById(R.id.imageButton4);
		r = (ImageButton) findViewById(R.id.imageButton5);
		t = (ImageButton) findViewById(R.id.imageButton6);
		y = (ImageButton) findViewById(R.id.imageButton26);
		u = (ImageButton) findViewById(R.id.imageButton2);
		i = (ImageButton) findViewById(R.id.imageButton7);
		o = (ImageButton) findViewById(R.id.imageButton8);
		p = (ImageButton) findViewById(R.id.imageButton9);
		a = (ImageButton) findViewById(R.id.imageButton10);
		s = (ImageButton) findViewById(R.id.imageButton11);
		d = (ImageButton) findViewById(R.id.imageButton12);
		f = (ImageButton) findViewById(R.id.imageButton13);
		g = (ImageButton) findViewById(R.id.imageButton14);
		h = (ImageButton) findViewById(R.id.imageButton15);
		j = (ImageButton) findViewById(R.id.imageButton16);
		k = (ImageButton) findViewById(R.id.imageButton17);
		l = (ImageButton) findViewById(R.id.imageButton18);
		z = (ImageButton) findViewById(R.id.imageButton19);
		x = (ImageButton) findViewById(R.id.imageButton20);
		c = (ImageButton) findViewById(R.id.imageButton21);
		v = (ImageButton) findViewById(R.id.imageButton22);
		b = (ImageButton) findViewById(R.id.imageButton23);
		n = (ImageButton) findViewById(R.id.imageButton24);
		m = (ImageButton) findViewById(R.id.imageButton25);
		q.setTag("q");
		w.setTag("w");
		e.setTag("e");
		r.setTag("r");
		t.setTag("t");
		y.setTag("y");
		u.setTag("u");
		i.setTag("i");
		o.setTag("o");
		p.setTag("p");
		a.setTag("a");
		s.setTag("s");
		d.setTag("d");
		f.setTag("f");
		g.setTag("g");
		h.setTag("h");
		j.setTag("j");
		k.setTag("k");
		l.setTag("l");
		z.setTag("z");
		x.setTag("x");
		c.setTag("c");
		v.setTag("v");
		b.setTag("b");
		n.setTag("n");
		m.setTag("m");
		buttons.add(q);
		buttons.add(w);
		buttons.add(e);
		buttons.add(r);
		buttons.add(t);
		buttons.add(y);
		buttons.add(u);
		buttons.add(i);
		buttons.add(o);
		buttons.add(p);
		buttons.add(a);
		buttons.add(s);
		buttons.add(d);
		buttons.add(f);
		buttons.add(g);
		buttons.add(h);
		buttons.add(j);
		buttons.add(k);
		buttons.add(l);
		buttons.add(z);
		buttons.add(x);
		buttons.add(c);
		buttons.add(v);
		buttons.add(b);
		buttons.add(n);
		buttons.add(m);
	
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_game, menu);
        return true;
    }

	public void onClick(View v) {
		Log.i("QWERTIE", "something pressed");
		if(v.getTag() != null) {
			checkLetter(((String)v.getTag()).charAt(0));
		}
		
	}
	
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
      // ignore orientation/keyboard change
      super.onConfigurationChanged(newConfig);
	}
	
	
	public void changeProgress (int progressDelta) {
    	progress+=progressDelta;
    	int progress = progressBar.getProgress();
    	progressBar.setProgress(progress);
    }
    
    public void increaseSuccess()
    {
    	completedWords++;
    	updateSuccessCounter();
    }
    
    public void updateSuccessCounter()
    {
    	TextView successCounter=(TextView) findViewById(R.id.success_counter);
        successCounter.setText(completedWords+"/"+targetNumOfWords);
    }
    
    public void updateScore(int scoreDelta)
    {
    	new CountDownTimer((scoreDelta)*6, 1) {
    	TextView scoreCounter=(TextView) findViewById(R.id.score_counter);
   	     public void onTick(long millisUntilFinished) {
   	    	score+=3;
    		scoreCounter.setText(score+"");
   	     }

   	     public void onFinish() {
   	     }
   	  }.start();
    }
    
    public void gameOver() {
    	musicFlag = true;
    	tickerFlag = true;
    	/*TODO: check if the code should be removed
    	 * Intent intent = new Intent(this, FinalScoreActivity.class);
    	intent.putExtra(levelTag, level);
    	Log.i("QWERTIE", "Level "+level+" passed in the intent");
    	intent.putExtra(FinalScoreActivity.successTag, FinalScoreActivity.GAME_SUCCESS);
    	 */
    	Dialog dialog = new Dialog(this);
         dialog.setContentView(R.layout.level_failed_dialog);
         dialog.setTitle("Level Failed");
         dialog.setCancelable(false);
         TextView scoreCounter=(TextView) findViewById(R.id.score_counter);
         for (int i=0; i<key_score_finish_word; i++)
         {
        	 score++;
        	 scoreCounter.setText(score+"");
         }
         TextView text = (TextView) dialog.findViewById(R.id.TextView01);
         text.setText("OOPS!");
         Button button = (Button) dialog.findViewById(R.id.Button01);
         button.setOnClickListener(new OnClickListener() {
         @Override
             public void onClick(View v) {
        		Intent intent = new Intent(getCurrentGameActivity(),GameActivity.class);
        	 	intent.putExtra(GameActivity.levelTag, level);
                 startActivity(intent);
              
             }
         });
         button = (Button) dialog.findViewById(R.id.Button02);
         button.setOnClickListener(new OnClickListener() {
             @Override
                 public void onClick(View v) {
            	   onBackPressed();
                 }
             });
         dialog.show();
    }
    
    public void gameWin() {
    	musicFlag = true;
    	tickerFlag = true;
    	/*TODO: check if the code should be removed
    	 * Intent intent = new Intent(this, FinalScoreActivity.class);
    	intent.putExtra(levelTag, level);
    	Log.i("QWERTIE", "Level "+level+" passed in the intent");
    	intent.putExtra(FinalScoreActivity.successTag, FinalScoreActivity.GAME_SUCCESS);
    	 */
    	SharedPreferences sharedPrefs = getSharedPreferences(MenuActivity.PREFS_NAME, 0);
        SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
        sharedPrefsEditor.putLong(MenuActivity.levelProgressTag, Math.max(1+level, sharedPrefs.getLong(MenuActivity.levelProgressTag, 0)));
    	sharedPrefsEditor.commit();
    	
    	Dialog dialog = new Dialog(this);
         dialog.setContentView(R.layout.level_completed_dialog);
         dialog.setTitle("Level Completed!");
         dialog.setCancelable(false);
         try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
		}
         TextView scoreCounter=(TextView) findViewById(R.id.score_counter);
         for (int i=0; i<key_score_finish_word; i++)
         {
        	 score++;
        	 scoreCounter.setText(score+"");
         }
         TextView text = (TextView) dialog.findViewById(R.id.TextView01);
         text.setText("Your Score is: " + score);
         Button button = (Button) dialog.findViewById(R.id.Button01);
         button.setOnClickListener(new OnClickListener() {
         @Override
             public void onClick(View v) {
             onBackPressed();
             }
         });
         dialog.show();
    }


    
    /**
     * Method will be called by clicking the buttons of the keyboard... TO DO
     * @param letter
     */
    public void checkLetter(char letter){
    	Log.i("QWERTIE", ""+letter+" pressed");
    	
    	int letter_color = currentLetter.getCurrentTextColor();
		
    	if(!currentLetter.getText().toString().equalsIgnoreCase("" + letter)) {
    		MediaPlayer mpBeep = MediaPlayer.create(this, R.raw.beep);
    		mpBeep.start();
    	}
    	
    	if(letter_color == YELLOW){
			Log.i("QWERTIE", currentLetter.getText().toString() + " ====== " + letter);
			if(currentLetter.getText().toString().equalsIgnoreCase("" + letter)){
				currentLetter.setTextColor(GREEN);
				if(currentLetterPos == currentWord.size()-1){
					if (errors == 0){
						successes++;
					}
					updateSuccessCounter();
					updateScore(key_score_finish_word);
					WordCompleted();
					
				}
				else {
					updateScore(key_score_first_try);
					currentLetterPos++;
					currentLetter = currentWord.get( currentLetterPos );
					currentLetter.setTextColor(YELLOW);
				}
			}
			else {
				currentLetter.setTextColor(ORANGE);
				errors++;
				successes = 0;
			}
		}
		else if(letter_color == ORANGE){
			if(currentLetter.getText().toString().equalsIgnoreCase("" + letter)){
				currentLetter.setTextColor(GREEN);
				updateScore(key_score_second_try);
				if(currentLetterPos == currentWord.size()-1){
					updateScore(key_score_finish_word);
					WordCompleted();
				}
				else{
					currentLetterPos++;
					currentLetter = currentWord.get( currentLetterPos );
					currentLetter.setTextColor(YELLOW);
				}
			}
			else {
				currentLetter.setTextColor(RED);
				errors++;
				successes = 0;
				
			}
		}
		else if(letter_color == RED){
			if(currentLetter.getText().toString().equalsIgnoreCase("" + letter)){
				currentLetter.setTextColor(GREEN);
				updateScore(key_score_third_try);
				if(currentLetterPos == currentWord.size()-1){
					updateScore(key_score_finish_word);
					WordCompleted();
				}
				else{
					currentLetterPos++;
					currentLetter = currentWord.get( currentLetterPos );
					currentLetter.setTextColor(YELLOW);
				}
			}
			else {
				gameOver();
			}
		}
    }
    
    /**
     * Takes a string and makes a list of TextView objects
     * @param word
     */
    public void displayWord(String word) {
    	int word_length = word.length();
    	List<TextView> letterList = new ArrayList<TextView>();
    	
    	LinearLayout wordLayout = (LinearLayout)findViewById(R.id.word_layout);
		wordLayout.removeAllViews();
    	
		int pixels = 40;
		int scale = 20;
		
    	while(word.length() > 0 ) {
    		
    		TextView textView = new TextView(this);
    		textView.setText(word.substring(0, 1));
    		word = word.substring(1);
    		textView.setTextColor(getResources().getColor(R.drawable.Black));
    		textView.setTypeface(Typeface.SERIF, 2);
    		textView.setTextSize(screenWidth/scale);
    		textView.setShadowLayer(1, 1, 1, SHADOW);
    		textView.setId(word_length - word.length() - 1); //because word.length() == word_length event at the first iteration
    		LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    		textView.setLayoutParams(textViewLayoutParams);
    		  
    		wordLayout.addView(textView);
    		
    		if(letterList.size() == 0)
    		textView.setPadding((screenWidth-word_length*pixels)/2, screenHeight/4, 0, 0);
    
    		
    		letterList.add(textView);
    	    }
    	
    	currentWord = letterList;
    	currentLetter = letterList.get(0);
    	currentLetter.setTextColor(YELLOW);
    	currentLetterPos = 0;
    	errors = 0;
   	}
    
    /**
     * Method is called when a word is completed and if it is not the last word load the next word, else level is cleared.
     */
    public void WordCompleted() {
    	currentWordPos ++;
    	if (currentWordPos == list_of_words.size()) {
    		gameWin();
    	}
    	else {
    		completedWords++;
    		updateSuccessCounter();
    		displayWord(list_of_words.get(currentWordPos));
    		
    	}
    }
    
    @Override
    public void onBackPressed() {
       musicFlag = true;
       Intent intent = new Intent(this, MenuActivity.class);
       startActivity(intent);
    }
	
}
